package com.zhaojun.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;

import java.util.Iterator;
import java.util.Map;

public class HttpServer {

    public static void main(String[] args) {
        NioEventLoopGroup boss=new NioEventLoopGroup();
        NioEventLoopGroup worker=new NioEventLoopGroup();
        ServerBootstrap bootstrap=new ServerBootstrap();
        bootstrap.group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler())
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new HttpRequestDecoder())
                                .addLast(new HttpObjectAggregator(65535))
                                .addLast(new HttpResponseEncoder())
                                .addLast(new SimpleChannelInboundHandler<HttpObject>() {
                                    protected void channelRead0(ChannelHandlerContext ctx, HttpObject fullHttpRequest) throws Exception {
                                        HttpHeaders headers = ((FullHttpRequest)fullHttpRequest).headers();
                                        Iterator<Map.Entry<String, String>> iter = headers.iteratorAsString();
                                        while (iter.hasNext()){
                                            Map.Entry<String, String> entry = iter.next();
                                            System.out.println(entry.getKey()+":"+entry.getValue());
                                        }
                                        String body="<html><head><title>你好！</title></head><body><span style='color:red'>你好，hello<span></body></html>";
                                        DefaultFullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.wrappedBuffer(body.getBytes("utf-8")));
                                        response.headers().add("content-type","text/html;charset=UTF-8");
                                        ChannelFuture f = ctx.writeAndFlush(response);
                                        f.addListener(ChannelFutureListener.CLOSE);
                                    }
                                });
                    }
                });


        try {
            ChannelFuture f = bootstrap.bind(8888).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
